<template>
  <div class="app-container">
    <!-- 巡检工单列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备巡检</span>
          <el-button type="primary" @click="showCreateDialog">新建巡检工单</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索工单号、设备名称..."
              clearable
            />
          </el-col>
          <el-col :span="16" style="text-align: right">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 巡检工单表格 -->
      <el-table
        :data="inspectionList"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="工单号" align="center" />
        <el-table-column prop="equipmentName" label="设备名称" align="center" />
        <el-table-column prop="type" label="巡检类型" align="center" />
        <el-table-column prop="status" label="巡检状态" align="center" >
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="plannedTime" label="计划时间" align="center"  />
        <el-table-column prop="executor" label="执行人" align="center" />
        <el-table-column label="操作" align="center"  fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === '待巡检'"
              size="small"
              type="primary"
              @click="startInspection(row)"
              >开始巡检</el-button
            >
            <el-button
              size="small"
              @click="showInspectionDetail(row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 巡检工单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="巡检工单详情"
      width="50%"
      top="5vh"
    >
      <div class="detail-content">
        <h3>基本信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="工单号">{{
            currentInspection.id
          }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{
            currentInspection.equipmentName
          }}</el-descriptions-item>
          <el-descriptions-item label="巡检类型">{{
            currentInspection.type
          }}</el-descriptions-item>
          <el-descriptions-item label="计划时间">{{
            currentInspection.plannedTime
          }}</el-descriptions-item>
          <el-descriptions-item label="执行人">{{
            currentInspection.executor
          }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{
            currentInspection.completedTime || "--"
          }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px">巡检项目</h3>
        <el-table :data="inspectionItems" border style="width: 100%">
          <el-table-column prop="name" label="项目名称"/>
          <el-table-column prop="standard" label="标准值"  />
          <el-table-column prop="actual" label="实际值"/>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="row.status === '正常' ? 'success' : 'danger'">
                {{ row.status || "未检验" }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <h3 style="margin-top: 20px">巡检照片</h3>
        <div class="image-preview">
          <el-image
            v-for="(image, index) in inspectionImages"
            :key="index"
            :src="image"
            :preview-src-list="inspectionImages"
            fit="cover"
            style="width: 100px; height: 100px; margin-right: 10px"
          />
        </div>

        <h3 style="margin-top: 20px">备注</h3>
        <el-input
          v-model="currentInspection.remark"
          type="textarea"
          :rows="3"
          readonly
          placeholder="无备注信息"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="exportPDF">导出PDF</el-button>
          <el-button @click="printInspection">打印</el-button>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 巡检操作对话框 -->
    <el-dialog
      v-model="operationDialogVisible"
      :title="'巡检操作 - ' + currentInspection.equipmentName"
      width="50%"
      top="5vh"
    >
      <div class="inspection-operation">
        <h3>工单号: {{ currentInspection.id }}</h3>

        <div
          v-for="(item, index) in inspectionItems"
          :key="index"
          class="inspection-item"
        >
          <h4>{{ item.name }}</h4>
          <p>标准值: {{ item.standard }}</p>
          <div v-if="item.name === '设备外观检查'">
            <el-input
              v-model="item.actual"
              type="textarea"
              :rows="2"
              placeholder="请输入检查结果"
            />
          </div>
          <div v-else>
            <el-radio-group v-model="item.status">
              <el-radio label="正常">正常</el-radio>
              <el-radio label="异常">异常</el-radio>
            </el-radio-group>
            <el-input
              v-if="item.status === '异常'"
              v-model="item.actual"
              type="textarea"
              :rows="2"
              placeholder="请输入异常说明"
              style="margin-top: 10px"
            />
          </div>
        </div>

        <h3 style="margin-top: 20px">巡检照片</h3>
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleUploadChange"
          :file-list="fileList"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <h3 style="margin-top: 20px">请输入实际值</h3>
        <el-input
          v-model="currentInspection.actual"
          type="text"
          placeholder="请输入实际值"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveInspection">保存</el-button>
          <el-button type="primary" @click="submitInspection">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新建巡检工单对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="新建巡检工单"
      width="50%"
      @close="resetCreateForm"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-width="120px"
      >
        <el-form-item label="设备名称" prop="equipmentName">
          <el-select
            v-model="createForm.equipmentName"
            placeholder="请选择设备"
            style="width: 100%"
          >
            <el-option
              v-for="item in equipmentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="巡检类型" prop="type">
          <el-select
            v-model="createForm.type"
            placeholder="请选择巡检类型"
            style="width: 100%"
          >
            <el-option label="日常巡检" value="日常巡检" />
            <el-option label="月度巡检" value="月度巡检" />
            <el-option label="季度巡检" value="季度巡检" />
            <el-option label="年度巡检" value="年度巡检" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间" prop="plannedTime">
          <el-date-picker
            v-model="createForm.plannedTime"
            type="datetime"
            placeholder="选择计划时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="执行人" prop="executor">
          <el-select
            v-model="createForm.executor"
            placeholder="请选择执行人"
            style="width: 100%"
          >
            <el-option
              v-for="item in executorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="createForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createInspection">确认创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

// 巡检工单列表相关
const loading = ref(false);
const inspectionList = ref([
  {
    id: "IN20230501001",
    equipmentName: "1号水泵",
    type: "日常巡检",
    status: "待巡检",
    plannedTime: "2023-05-01 08:00",
    executor: "张明远",
    completedTime: "",
    remark: "",
  },
  {
    id: "IN20230501002",
    equipmentName: "2号水泵",
    type: "日常巡检",
    status: "待巡检",
    plannedTime: "2023-05-01 09:00",
    executor: "李华",
    completedTime: "",
    remark: "",
  },
  {
    id: "IN20230501003",
    equipmentName: "3号水泵",
    type: "日常巡检",
    status: "待巡检",
    plannedTime: "2023-05-01 10:00",
    executor: "王建国",
    completedTime: "",
    remark: "",
  },
  {
    id: "IN20230501004",
    equipmentName: "4号水泵",
    type: "日常巡检",
    status: "待巡检",
    plannedTime: "2023-05-01 11:00",
    executor: "赵晓丽",
    completedTime: "",
    remark: "",
  },
  {
    id: "IN20230501005",
    equipmentName: "5号水泵",
    type: "日常巡检",
    status: "待巡检",
    plannedTime: "2023-05-01 13:00",
    executor: "陈志强",
    completedTime: "",
    remark: "",
  },
  {
    id: "IN20230501006",
    equipmentName: "1号阀门",
    type: "月度巡检",
    status: "待巡检",
    plannedTime: "2023-05-01 15:00",
    executor: "刘芳",
    completedTime: "",
    remark: "",
  },
  {
    id: "IN20230501007",
    equipmentName: "2号阀门",
    type: "月度巡检",
    status: "待巡检",
    plannedTime: "2023-05-01 16:00",
    executor: "孙伟",
    completedTime: "",
    remark: "",
  },
  {
    id: "IN20230501008",
    equipmentName: "3号阀门",
    type: "月度巡检",
    status: "已完成",
    plannedTime: "2023-05-02 08:00",
    executor: "周婷",
    completedTime: "2023-05-02 09:30",
    remark: "设备运行正常",
  },
  {
    id: "IN20230501009",
    equipmentName: "1号电机",
    type: "季度巡检",
    status: "已完成",
    plannedTime: "2023-05-02 09:00",
    executor: "吴刚",
    completedTime: "2023-05-02 11:15",
    remark: "发现轻微振动，已调整",
  },
  {
    id: "IN20230501010",
    equipmentName: "2号电机",
    type: "季度巡检",
    status: "已完成",
    plannedTime: "2023-05-02 13:00",
    executor: "郑秀英",
    completedTime: "2023-05-02 14:45",
    remark: "设备运行正常",
  },
]);

// 搜索表单
const searchForm = reactive({
  keyword: "",
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 35,
});

// 当前查看的巡检工单
const currentInspection = ref({});

// 巡检项目数据
const inspectionItems = ref([
  {
    name: "设备外观检查",
    standard: "无破损、无锈蚀",
    actual: "",
    status: "",
  },
  {
    name: "运行声音检查",
    standard: "无异常噪音",
    actual: "",
    status: "",
  },
  {
    name: "振动检查",
    standard: "振幅≤0.05mm",
    actual: "",
    status: "",
  },
  {
    name: "温度检查",
    standard: "≤65℃",
    actual: "",
    status: "",
  },
  {
    name: "压力检查",
    standard: "0.3~0.5MPa",
    actual: "",
    status: "",
  },
  {
    name: "润滑油检查",
    standard: "油位在1/2~2/3之间",
    actual: "",
    status: "",
  },
]);

// 巡检照片
const inspectionImages = ref([
  "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
  "https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg",
  "https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg",
]);

// 上传文件列表
const fileList = ref([]);

// 设备选项
const equipmentOptions = [
  { value: "1号水泵", label: "1号水泵" },
  { value: "2号水泵", label: "2号水泵" },
  { value: "3号水泵", label: "3号水泵" },
  { value: "4号水泵", label: "4号水泵" },
  { value: "5号水泵", label: "5号水泵" },
  { value: "1号阀门", label: "1号阀门" },
  { value: "2号阀门", label: "2号阀门" },
  { value: "3号阀门", label: "3号阀门" },
  { value: "1号电机", label: "1号电机" },
  { value: "2号电机", label: "2号电机" },
];

// 执行人选项
const executorOptions = [
  { value: "张明远", label: "张明远" },
  { value: "李华", label: "李华" },
  { value: "王建国", label: "王建国" },
  { value: "赵晓丽", label: "赵晓丽" },
  { value: "陈志强", label: "陈志强" },
  { value: "刘芳", label: "刘芳" },
  { value: "孙伟", label: "孙伟" },
  { value: "周婷", label: "周婷" },
  { value: "吴刚", label: "吴刚" },
  { value: "郑秀英", label: "郑秀英" },
];

// 对话框控制
const detailDialogVisible = ref(false);
const operationDialogVisible = ref(false);
const createDialogVisible = ref(false);

// 新建巡检工单表单
const createForm = reactive({
  equipmentName: "",
  type: "",
  plannedTime: "",
  executor: "",
  remark: "",
});

const createRules = {
  equipmentName: [
    { required: true, message: "请选择设备名称", trigger: "change" },
  ],
  type: [{ required: true, message: "请选择巡检类型", trigger: "change" }],
  plannedTime: [
    { required: true, message: "请选择计划时间", trigger: "change" },
  ],
  executor: [{ required: true, message: "请选择执行人", trigger: "change" }],
};

const createFormRef = ref(null);

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case "已完成":
      return "success";
    case "待巡检":
      return "warning";
    case "已取消":
      return "info";
    default:
      return "";
  }
};

// 显示巡检详情对话框
const showInspectionDetail = (inspection) => {
  currentInspection.value = inspection;
  detailDialogVisible.value = true;
};

// 开始巡检操作
const startInspection = (inspection) => {
  currentInspection.value = inspection;
  operationDialogVisible.value = true;
  
  // 重置巡检项目状态
  inspectionItems.value.forEach(item => {
    item.actual = "";
    item.status = "";
  });
  fileList.value = [];
};

// 处理上传文件变化
const handleUploadChange = (file, fileList) => {
  // 这里可以处理文件上传逻辑
  console.log(file, fileList);
};

// 保存巡检结果
const saveInspection = () => {
  ElMessage.success("巡检结果已保存");
  operationDialogVisible.value = false;
};

// 提交巡检结果
const submitInspection = () => {
  ElMessageBox.confirm("确认提交巡检结果吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 更新巡检状态为已完成
      const index = inspectionList.value.findIndex(
        (item) => item.id === currentInspection.value.id
      );
      if (index !== -1) {
        inspectionList.value[index].status = "已完成";
        inspectionList.value[index].completedTime = new Date().toLocaleString();
      }
      ElMessage.success("巡检结果已提交");
      operationDialogVisible.value = false;
    })
    .catch(() => {
      ElMessage.info("已取消提交");
    });
};

// 导出PDF
const exportPDF = () => {
  ElMessage.success("导出PDF成功");
};

// 打印
const printInspection = () => {
  ElMessage.success("打印功能已调用");
};

// 显示新建巡检工单对话框
const showCreateDialog = () => {
  createDialogVisible.value = true;
};

// 创建巡检工单
const createInspection = () => {
  createFormRef.value.validate((valid) => {
    if (valid) {
      // 生成新的工单ID
      const newId = `IN${new Date().getFullYear()}${(new Date().getMonth() + 1)
        .toString()
        .padStart(2, "0")}${new Date()
        .getDate()
        .toString()
        .padStart(2, "0")}${Math.floor(Math.random() * 1000)
        .toString()
        .padStart(3, "0")}`;

      // 添加新工单
      inspectionList.value.unshift({
        id: newId,
        equipmentName: createForm.equipmentName,
        type: createForm.type,
        status: "待巡检",
        plannedTime: createForm.plannedTime,
        executor: createForm.executor,
        completedTime: "",
        remark: createForm.remark,
      });

      ElMessage.success("巡检工单创建成功");
      createDialogVisible.value = false;
      pagination.total += 1;
    }
  });
};

// 重置新建表单
const resetCreateForm = () => {
  createFormRef.value?.resetFields();
  createForm.remark = "";
};

// 处理搜索
const handleSearch = () => {
  loading.value = true;
  // 模拟搜索
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  // 这里可以调用获取数据的方法
};

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  // 这里可以调用获取数据的方法
};

// 初始化数据
onMounted(() => {
  // 这里可以调用获取数据的API
});
</script>

<style scoped>

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  padding: 15px;
}

.detail-content h3 {
  margin-bottom: 15px;
  color: #409eff;
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.inspection-operation {
  padding: 15px;
}

.inspection-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.inspection-item h4 {
  margin-bottom: 10px;
  color: #606266;
}

.inspection-item p {
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}
</style>